<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">职位管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="positions" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="职位"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增职位
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="职位名称">
          <el-input v-model="searchForm.name" placeholder="请输入职位名称" clearable />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="searchForm.departmentId" placeholder="请选择部门" clearable>
            <el-option label="技术部" :value="1" />
            <el-option label="市场部" :value="2" />
            <el-option label="人事部" :value="3" />
            <el-option label="财务部" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchEnable">批量启用</el-button>
              <el-button size="small" type="warning" @click="handleBatchDisable">批量停用</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="code" label="职位代码" width="120" />
        <el-table-column prop="name" label="职位名称" width="150" />
        <el-table-column prop="departmentName" label="所属部门" width="120" />
        <el-table-column prop="level" label="职级" width="120">
          <template #default="{ row }">
            <el-tag :type="getLevelTag(row.level)">{{ getLevelLabel(row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="employeeCount" label="在职人数" width="100" />
        <el-table-column prop="salary" label="基础薪资" width="120">
          <template #default="{ row }">
            {{ row.salary ? '¥' + row.salary.toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button 
              link 
              :type="row.status === 1 ? 'warning' : 'success'" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="职位代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入职位代码" />
        </el-form-item>
        <el-form-item label="职位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择部门">
            <el-option label="技术部" :value="1" />
            <el-option label="市场部" :value="2" />
            <el-option label="人事部" :value="3" />
            <el-option label="财务部" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="职级" prop="level">
          <el-select v-model="form.level" placeholder="请选择职级">
            <el-option label="初级" value="junior" />
            <el-option label="中级" value="middle" />
            <el-option label="高级" value="senior" />
            <el-option label="专家" value="expert" />
            <el-option label="管理层" value="manager" />
          </el-select>
        </el-form-item>
        <el-form-item label="基础薪资" prop="salary">
          <el-input-number v-model="form.salary" :min="0" :step="1000" />
          <span class="form-tip">单位：元</span>
        </el-form-item>
        <el-form-item label="岗位职责" prop="responsibility">
          <el-input 
            v-model="form.responsibility" 
            type="textarea" 
            :rows="3"
            placeholder="请输入岗位职责" 
          />
        </el-form-item>
        <el-form-item label="任职要求" prop="requirements">
          <el-input 
            v-model="form.requirements" 
            type="textarea" 
            :rows="3"
            placeholder="请输入任职要求" 
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  departmentId: null
})

// 选中的行
const selectedRows = ref([])

// 导出列配置
const exportColumns = [
  { prop: 'code', label: '职位代码' },
  { prop: 'name', label: '职位名称' },
  { prop: 'departmentName', label: '所属部门' },
  { prop: 'level', label: '职级' },
  { prop: 'salary', label: '基础薪资' },
  { prop: 'status', label: '状态' },
  { prop: 'remark', label: '备注' }
]

// 表格数据
const tableData = ref([
  { id: 1, code: 'POS001', name: '软件工程师', departmentName: '技术部', departmentId: 1, level: 'middle', employeeCount: 15, salary: 12000, status: 1, responsibility: '负责系统开发和维护', requirements: '3年以上开发经验', remark: '' },
  { id: 2, code: 'POS002', name: '高级工程师', departmentName: '技术部', departmentId: 1, level: 'senior', employeeCount: 8, salary: 18000, status: 1, responsibility: '负责核心技术研发', requirements: '5年以上开发经验', remark: '' },
  { id: 3, code: 'POS003', name: '产品经理', departmentName: '市场部', departmentId: 2, level: 'middle', employeeCount: 5, salary: 15000, status: 1, responsibility: '负责产品规划和设计', requirements: '3年以上产品经验', remark: '' },
  { id: 4, code: 'POS004', name: '市场专员', departmentName: '市场部', departmentId: 2, level: 'junior', employeeCount: 10, salary: 8000, status: 1, responsibility: '负责市场推广', requirements: '1年以上市场经验', remark: '' },
  { id: 5, code: 'POS005', name: '人事主管', departmentName: '人事部', departmentId: 3, level: 'manager', employeeCount: 2, salary: 13000, status: 1, responsibility: '负责人事管理', requirements: '5年以上人事经验', remark: '' },
  { id: 6, code: 'POS006', name: '财务经理', departmentName: '财务部', departmentId: 4, level: 'manager', employeeCount: 3, salary: 16000, status: 1, responsibility: '负责财务管理', requirements: '5年以上财务经验', remark: '' }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 6
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增职位')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  departmentId: null,
  level: '',
  salary: 0,
  responsibility: '',
  requirements: '',
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入职位代码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  level: [{ required: true, message: '请选择职级', trigger: 'change' }]
}

// 获取职级标签
const getLevelTag = (level) => {
  const tagMap = {
    junior: '',
    middle: 'success',
    senior: 'warning',
    expert: 'danger',
    manager: 'primary'
  }
  return tagMap[level] || ''
}

// 获取职级名称
const getLevelLabel = (level) => {
  const labelMap = {
    junior: '初级',
    middle: '中级',
    senior: '高级',
    expert: '专家',
    manager: '管理层'
  }
  return labelMap[level] || level
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.departmentId = null
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量启用
const handleBatchEnable = () => {
  ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个职位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedRows.value.forEach(row => {
      row.status = 1
    })
    ElMessage.success('批量启用成功')
    selectedRows.value = []
  })
}

// 批量停用
const handleBatchDisable = () => {
  ElMessageBox.confirm(`确定要停用选中的 ${selectedRows.value.length} 个职位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedRows.value.forEach(row => {
      row.status = 0
    })
    ElMessage.success('批量停用成功')
    selectedRows.value = []
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个职位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    console.log('批量删除:', ids)
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    handleSearch()
  })
}

// 导入成功回调
const handleImportSuccess = (result) => {
  console.log('导入成功:', result)
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增职位'
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    departmentId: null,
    level: '',
    salary: 0,
    responsibility: '',
    requirements: '',
    sort: 0,
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑职位'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除职位 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log('删除:', row.id)
    ElMessage.success('删除成功')
  })
}

// 切换状态
const handleToggleStatus = (row) => {
  const status = row.status === 1 ? 0 : 1
  const text = status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确定要${text}职位 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = status
    ElMessage.success(`${text}成功`)
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.form-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style>

